package com.example.mybatispdemo.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.mybatispdemo.store.entity.ProductEntity;
import com.example.mybatispdemo.store.dao.ProductDao;
import com.example.mybatispdemo.store.exception.ProductException;
import com.example.mybatispdemo.store.service.IProductService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ljp
 * @since 2022-10-29
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductDao, ProductEntity> implements IProductService {


    @Override
    public boolean addProduct(ProductEntity product) {
        if(this.getById(product.getId())!=null){
            return false;
        }
        return this.save(product);
    }

    @Override
    public ProductEntity getProductById(Integer id) throws ProductException {
        if(id == null){
            throw new ProductException("商品id不能为空！");
        }
        if(this.getById(id) == null){
            throw new ProductException("商品id不存在！");
        }
        return this.getById(id);
    }

    @Override
    public List<ProductEntity> getProductByName(String name) throws ProductException{
        if(name==null){
            throw new ProductException("商品id不能为空！");
        }
        QueryWrapper<ProductEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().like(ProductEntity::getName,name);
        return this.list(queryWrapper);
    }

    @Override
    public List<ProductEntity> getProuctByNameQuantity(String name, Float quantity) throws ProductException{
        if(name==null || quantity==null){
            throw new ProductException("商品名称或者数量不能为空！");
        }
        QueryWrapper<ProductEntity>queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().like(ProductEntity::getName,name).ge(ProductEntity::getStockQuantity,quantity);
        return this.list(queryWrapper);
    }

    @Override
    public boolean updateProductById(Integer id,ProductEntity product) {
        ProductEntity product1 = this.getById(id);
        if(product1==null){
            return false;
        }
        return this.updateById(product);
    }

    @Override
    public boolean deleteProductById(Integer id) {
        ProductEntity product1 = this.getById(id);
        if(product1==null){
            return false;
        }
        QueryWrapper<ProductEntity>queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(ProductEntity::getId,id);
        this.baseMapper.delete(queryWrapper);
        return true;
    }

    @Override
    public boolean deleteAll() {
        QueryWrapper<ProductEntity>queryWrapper=new QueryWrapper<>();
        this.baseMapper.delete(queryWrapper);
        return true;
    }
}
